package com.ruiben.mall.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruiben.mall.IAttributeService;
import com.ruiben.mall.mapper.AttributeMapper;
import com.ruiben.mall.pojo.Attribute;
import com.ruiben.mall.utils.PagedResult;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class AttributeServiceImpl implements IAttributeService {


    @Autowired
    private AttributeMapper attributeMapper;

    @Autowired
    private Sid sid;

    /**
     * 根据类型id获取当前属性列表
     * @param page 页数
     * @param typeId 类型id
     * @return
     */
    @Override
    public PagedResult getAttributeList(int page, int pageSize, String typeId) {




        PageHelper.startPage(page, pageSize);
        List<Attribute> attributes = attributeMapper.getAttrByTypeId(typeId);
        for (Attribute attr:attributes){
            if (!StringUtils.isBlank(attr.getAttrValues())){
                String replace = attr.getAttrValues().replace("\r\n", ",");
                attr.setAttrValues(replace);

            }
        }
        PageInfo<Attribute> pageList = new PageInfo<>(attributes);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(attributes);
        pagedResult.setRecords(pageList.getTotal());

//        return ""
        return pagedResult;
    }

    /**
     * 根据类型id获取当前属性列表
     * @param typeId 类型id
     * @return
     */
    @Override
    public List<Attribute> getAttributeList(String typeId, int attrType) {

//        Example example = new Example(Attribute.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("typeId",typeId);

        List<Attribute> attributes = attributeMapper.getAttrByTypeIdForType(typeId,attrType);

//        List<Attribute> attributes = attributeMapper.selectByExample(example);
        for (Attribute attr:attributes){
            if (!StringUtils.isBlank(attr.getAttrValues())){
                String[] split = attr.getAttrValues().split("\r\n");
                attr.setValues(new ArrayList<String>(Arrays.asList(split)));

            }
        }

        return attributes;
    }



    @Override
    public Attribute getAttributeById(String id) {
        return attributeMapper.selectByPrimaryKey(id);
    }

}
